package com.ht.api.handler;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ht.api.util.IpUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 接口访问耗时
 * @author asq
 * @createTime 2024年12月21日 19:29:55
 */
@Slf4j
@Component
public class TimeHandler implements HandlerInterceptor {
	private ThreadLocal<Long> local = new ThreadLocal<>();

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object obj, Exception e)
			throws Exception {
		long time = System.currentTimeMillis() - local.get();
		log.info("[鉴权]通过，IP[{}]访问接口成功！ 耗时:{}ms", IpUtils.getIpAddr(), time);
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse res, Object obj, ModelAndView mav)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object obj) throws Exception {
		local.set(System.currentTimeMillis());
		return true;
	}

}